<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas 绘制文字</title>
    <style>
      body{
        background: #666;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      canvas{
        background: #fff;
      }
      a{
        color: #fff;
        font-size: 24px;
      }
    </style>
</head>
<body>
    <!-- 
      
    -->
    <ul>
      <li><a href="#绘制文字">绘制文字</a></li>
    </ul>
    <div>
      <a id="绘制文字"></a>
      <h1>绘制文字</h1>
      <canvas id="canvas1" width="500" height="500"></canvas>
      <script>

        const drawLine = () => {
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(250, 0);
          ctx.lineTo(250, 500);
          ctx.moveTo(0, 250);
          ctx.lineTo(500, 250);
          ctx.strokeStyle = '#999';
          ctx.stroke();
          ctx.closePath();
          ctx.restore();
        }

        const drawText = (
          str,
          x, y,
          fontSize = 50, 
          width = 300
        ) => {
          ctx.font = `${fontSize}px bold 宋体`
          while(ctx.measureText(str).width > 300) {
            fontSize--
            ctx.font = `${fontSize}px bold 宋体`
          }
          ctx.textAlign = 'center'
          ctx.textBaseline = 'middle'

          ctx.fillStyle = 'red'
          ctx.fillText(str, x, y)
        }


        let oCanvas = document.getElementById('canvas1')
        let ctx = oCanvas.getContext('2d'); //拿到画笔

        drawLine()

        ctx.font = 'bold 70px 宋体'
        ctx.textAlign = 'center'
          // 调节横向排版: 值为 start, center, end, left, right
        ctx.textBaseline = 'middle'
          // 调节纵向排版: 值为 top, bottom, middle 等
        // ctx.fillStyle = 'red'
        // ctx.fillText('程序员小石', 250, 250)

        // ctx.strokeStyle = 'red'
        // ctx.strokeText('程序员小石', 250, 250)

        // console.log(
        //   ctx.measureText('程序员小石')
        // )

        drawText('抖音中的程序员:100px', 250, 50, 100)
        drawText('程序员小石: 100px',   250, 150, 100)
        drawText('小石:100px',          250, 250, 100)

      </script>
    </div>
</body>
</html>
